<template>
  <div>
    <!-- <div class="w">
      <Alert show-icon closable type="warning" class="tips-box">
        小提示
        <Icon type="ios-lightbulb-outline" slot="icon"></Icon>
        <template slot="desc">请点击商品前的选择框，选择购物车中的商品，点击付款即可。</template>
      </Alert>
    </div> -->
    <div class="search-nav">
      <div class="search-nav-container w">
        <ul>
          <li>我的购物车</li>
        </ul>
      </div>
    </div>
    <div class="w">
      <el-table ref="myTable" :data="myCarData" border style="width: 100%" class="order-table" @selection-change="handleSelectionChange" :height="tableHeight">
        <template slot="empty">
          <p class="emptyText">您的购物车没有商品，请先
            <router-link class="link-type" :to="'/'"><span style="cursor: pointer;">添加商品</span> </router-link>
            到购物车再点击购买
          </p>
        </template>
        <el-table-column type="selection" width="44" align="center">
        </el-table-column>
        <el-table-column label="商品快照" width="130px">
          <template slot-scope="scope">
            <img :src="scope.row.picture" style="height:80px;width:100px;" alt="" srcset="">
          </template>
        </el-table-column>
        <el-table-column prop="commodity" label="标题" width="180">
        </el-table-column>
        <el-table-column prop="price" label="价格">
        </el-table-column>
        <el-table-column prop="addNumber" label="数量">
          <template slot-scope="scope">
            <el-input-number @change="addNumberChange(scope.row)" v-model="scope.row.addNumber" :min="1" :max="10"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template slot-scope="scope">
            <i class="el-icon-circle-close" @click="deleteGoods(scope.row)"></i>
            <!-- <el-button type="danger" size="mini" icon="el-icon-magic-delete" @click="deleteGoods(scope.row)">从购物车移出</el-button></el-button> -->

          </template>
        </el-table-column>
      </el-table>
      <!-- 收货人信息 -->
      <!-- <div class="address-container">
        <h3>收货人信息</h3>
        <div class="address-box">
          <div class="address-check">
            <div class="address-check-name">
              <span>
                <Icon type="ios-checkmark-outline"></Icon> {{checkAddress.name}}
              </span>
            </div>
            <div class="address-detail">
              <p>{{checkAddress.address}}</p>
            </div>
          </div>
          <Collapse>
            <Panel>
              选择地址
              <p slot="content">
                <RadioGroup vertical size="large" @on-change="changeAddress">
                  <Radio :label="item.addressId" v-for="(item, index) in $store.state.goodsDetail.userAddress" :key="index">
                    <span>{{item.name}} {{item.province}} {{item.city}} {{item.address}} {{item.phone}} {{item.postalcode}}</span>
                  </Radio>
                </RadioGroup>
              </p>
            </Panel>
          </Collapse>
        </div>
      </div>
      <div class="remarks-container">
        <h3>备注</h3>
        <el-input class="remarks-input" type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="在这里填写备注信息" v-model="textaremarksrea2">
        </el-input>
      </div> -->
      <div class="pay-container">
        <div class="pay-box">
          <p><span>商品总额：</span> <span class="money">
              <Icon type="social-yen"></Icon> {{totalPrice.toFixed(2)}}
            </span></p>
          <div class="pay-btn">
            <Button style="margin-right:12px;" type="error" size="large" @click="resetShopCar()">清空购物车</Button></Button>
            <Button type="error" :disabled="goodsCheckList.length == 0" size="large" @click="order()">提交订单</Button>
          </div>
        </div>
      </div>
    </div>
  </div>

</template>

<script>
import { goOrder, getShoppingCartList, orderSave, removeShoppingCart, clearShoppingCart } from '@/api/goods'
export default {
  data() {
    return {
      tableHeight: 200,
      myCarData: [],
      checkAddress: {
        name: '未选择',
        address: '请选择地址'
      },
      remarks: '',
      goodsCheckList: [],
    }
  },
  created() {
    // this.$store.dispatch("loadAddress")
    this.getCarList()
  },
  mounted() {
    var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
    this.$nextTick(function () {
      this.tableHeight = h - 506
      // 监听窗口大小变化
      let self = this
      window.onresize = function () {
        self.tableHeight = h -  506
      }
    })
  },
  computed: {
    totalPrice() {
      let price = 0;
      this.goodsCheckList.forEach(item => {
        price += item.price * item.addNumber;
      });
      return price;
    }
  },
  methods: {
    getCarList() {
      getShoppingCartList().then(res => {
        this.myCarData = res.data
      })
    },
    handleSelectionChange(e) {
      this.goodsCheckList = e;
    },
    addNumberChange(row) {
      // 同步多选数据
      if (this.goodsCheckList.length > 0) {
        this.goodsCheckList.forEach(item => {
          if (item.id == row.id) {
            item.addNumber = row.addNumber
          }
        })
      }
    },
    changeAddress(data) {
      const father = this;
      this.$store.state.goodsDetail.userAddress.forEach(item => {
        if (item.addressId === data) {
          father.checkAddress.name = item.name;
          father.checkAddress.address = `${item.name} ${item.province} ${item.city} ${item.address} ${item.phone} ${item.postalcode}`;
        }
      })
    },
    // 删除某个商品
    deleteGoods(row) {
      this.$modal.confirm('是否将' + row.commodity + '移出购物车').then(() => {
        removeShoppingCart({ id: row.id }).then(res => {
          this.$modal.msgSuccess('已成功从购物车移出')
          this.getCarList()
        })
      }).catch(e => { })
    },
    // 清空购物车
    resetShopCar() {
      this.$modal.confirm('是否清空购物车').then(() => {
        clearShoppingCart().then(res => {
          this.$modal.msgSuccess('清空购物车成功')
          this.getCarList()
        })
      }).catch(e => { })
    },
    order() {
      if (this.goodsCheckList.length > 0) {
        let saveOrderList = JSON.parse(JSON.stringify(this.goodsCheckList))
        // 生成订单 替换需要的字段名称
        saveOrderList = JSON.parse(JSON.stringify(saveOrderList).replace(/id/g, "shopId").replace(/userId/g, "businessId"));

        // totalAmount
        saveOrderList.forEach(item => {
          item.status = 1
          item.totalAmount = item.addNumber * item.price
        })
        // 调用生成订单接口
        orderSave(saveOrderList).then(res => {
          // 刷新购物车
          // this.getCarList()
          this.$router.push({ path: '/orderList' }).catch(() => { });
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
  .tips-box {
    margin-top: 12px;
  }

  // 表格
  .order-table {
    margin-bottom: 12px;
  }
  // 收货人信息i
  .address-container {
    margin-top: 15px;
  }
  .address-box {
    margin-top: 15px;
    padding: 15px;
    border: 1px #ccc dotted;
  }
  .address-check {
    margin: 15px 0px;
    height: 36px;
    display: flex;
    align-items: center;
  }
  .address-check-name {
    width: 120px;
    display: flex;
    justify-content: center;
    align-content: center;
    background-color: #ccc;
  }
  .address-check-name span {
    width: 120px;
    height: 36px;
    font-size: 14px;
    line-height: 36px;
    text-align: center;
    color: #fff;
    background-color: #d7593e;
  }
  .address-detail {
    padding-left: 15px;
    font-size: 14px;
    color: #999999;
  }

  .remarks-container {
    margin: 15px 0px;
  }
  .remarks-input {
    margin-top: 15px;
  }
  // 支付
  .pay-container {
    margin: 15px;
    display: flex;
    justify-content: flex-end;
  }
  .pay-box {
    font-size: 18px;
    font-weight: bolder;
    color: #495060;
  }
  .money {
    font-size: 26px;
    color: #f90013;
  }
  .pay-btn {
    margin: 15px 0px;
    display: flex;
    justify-content: flex-end;
  }
</style>